﻿using MediatR;
using Microsoft.Extensions.Logging;
using Service.Framework.Utils;
using System.Diagnostics;

namespace Service.Core.Behaviors
{
    /// <summary>
    /// 消息分发管道
    /// </summary>
    /// <typeparam name="TRequest"></typeparam>
    /// <typeparam name="TResponse"></typeparam>
    public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : MediatR.IRequest<TResponse>
    {
        private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;

        /// <summary>
        /// 
        /// </summary>
        public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
        {
            _logger = logger;
        }

        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next,
            CancellationToken cancellationToken)
        {
            Stopwatch stopwatch = new();
            _logger.LogInformation(
                $"----- 处理指令 ({request.GetGenericTypeName()})  ({JsonSerializeUtil.SerializeObject(request, formatting: Newtonsoft.Json.Formatting.None)}) ");
            var response = await next();
            stopwatch.Stop();
            _logger.LogInformation(
                $"----- 指令返回 【{request.GetGenericTypeName()}】 in 【{stopwatch.ElapsedMilliseconds}】 ms ({JsonSerializeUtil.SerializeObject(response, Newtonsoft.Json.Formatting.None)})");
            stopwatch.Reset();
            return response;
        }
    }
}